package com.ys.filelib.filedialog;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;

public class StorageReceiver extends BroadcastReceiver {

    private Context mContext;
    private OnStateListener mStateListener;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Uri data = intent.getData();
        if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
            if (mStateListener != null) {
                mStateListener.onStorageIn(data.getPath());
            }
        }
        if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
            if (mStateListener != null) {
                mStateListener.onStorageOut(data.getPath());
            }
        }
    }

    public void register(Context context) {
        this.mContext = context;
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        filter.addAction(Intent.ACTION_MEDIA_EJECT);
        filter.addDataScheme("file");
        context.registerReceiver(this, filter);
    }

    public void unregister() {
        if (mContext != null) {
            mContext.unregisterReceiver(this);
        }
    }

    public void setStateListener(OnStateListener listener) {
        this.mStateListener = listener;
    }

    public interface OnStateListener {
        void onStorageIn(String path);
        void onStorageOut(String path);
    }
}
